<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request, { SERVER_BASE_URL } from "@/utils/request.js"

// 路由实例
const router = useRouter()

// 用户ID
const userId = ref(null)
// 结算商品列表
const cartItems = ref([])
// 地址列表
const addressList = ref([])
// 选中的地址ID
const selectedAddressId = ref(null)
// 支付方式
const paymentType = ref('ONLINE')
// 订单备注
const orderRemark = ref('')
// 加载状态
const loading = ref(false)
// 创建订单状态
const creatingOrder = ref(false)

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.quantity * item.commodity.price
  }, 0)
})

// 计算总商品数量
const totalQuantity = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.quantity
  }, 0)
})

// 检查登录状态
const checkLoginStatus = () => {
  const userInfo = JSON.parse(localStorage.getItem('user'))
  if (!userInfo) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return false
  }
  
  userId.value = userInfo.id
  return true
}

// 获取结算商品列表
const getCheckoutItems = () => {
  const items = localStorage.getItem('checkoutItems')
  if (!items) {
    ElMessage.warning('没有选择结算商品，返回购物车')
    router.push('/cart')
    return false
  }
  
  cartItems.value = JSON.parse(items)
  return true
}

// 获取用户地址列表
const getAddressList = async () => {
  if (!checkLoginStatus()) return
  
  loading.value = true
  try {
    const res = await request.get('/address/list', {
      params: { userId: userId.value }
    })
    if (res.code === 200) {
      addressList.value = res.data
      
      // 如果有默认地址，则选中默认地址
      const defaultAddress = addressList.value.find(addr => addr.isDefault)
      if (defaultAddress) {
        selectedAddressId.value = defaultAddress.id
      } else if (addressList.value.length > 0) {
        // 否则选中第一个地址
        selectedAddressId.value = addressList.value[0].id
      }
    } else {
      ElMessage.error(res.message || '获取地址列表失败')
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  } finally {
    loading.value = false
  }
}

// 添加新地址
const addNewAddress = () => {
  // 跳转到地址管理页面
  router.push('/personal/address')
}

// 提交订单
const submitOrder = async () => {
  if (!checkLoginStatus()) return
  
  // 验证必要信息
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择收货地址')
    return
  }
  
  creatingOrder.value = true
  try {
    // 构建订单数据
    const orderData = {
      order: {
        userId: userId.value,
        addressId: selectedAddressId.value,
        paymentType: paymentType.value,
        totalAmount: totalPrice.value,
        actualAmount: totalPrice.value, // 实际支付金额，后续可加入优惠折扣逻辑
        remark: orderRemark.value,
        isPaidDirectly: paymentType.value === 'CASH' // 如果是货到付款，设置为已付款状态
      },
      items: cartItems.value.map(item => ({
        commodityId: item.commodity.id,
        commodityName: item.commodity.name,
        commodityPrice: item.commodity.price,
        quantity: item.quantity,
        subtotal: item.quantity * item.commodity.price
      }))
    }
    
    // 调用创建订单接口
    const res = await request.post('/order/create', orderData)
    
    if (res.code === 200) {
      ElMessage.success('订单创建成功')
      
      // 订单创建成功后，需要从购物车中删除这些商品
      await deleteCartItems()
      
      // 清除本地缓存
      localStorage.removeItem('checkoutItems')
      
      // 跳转到订单详情页面
      router.push(`/order/${res.data.orderNo}`)
    } else {
      ElMessage.error(res.message || '创建订单失败')
    }
  } catch (error) {
    console.error('创建订单失败:', error)
    ElMessage.error('创建订单失败')
  } finally {
    creatingOrder.value = false
  }
}

// 从购物车中删除已结算的商品
const deleteCartItems = async () => {
  try {
    // 筛选出真实购物车中的商品ID（非临时ID）
    // 直接购买的商品ID是临时生成的（Date.now()），通常是13位数字
    const cartItemIds = cartItems.value
      .filter(item => {
        // 判断是否为购物车中的商品（ID应该是数据库中的ID，通常较小）
        // 临时ID（从商品详情页直接购买生成的）通常很大（时间戳）
        return typeof item.id === 'number' && item.id < 1000000;
      })
      .map(item => item.id);
    
    // 如果没有需要删除的购物车商品，直接返回
    if (cartItemIds.length === 0) {
      return true;
    }
    
    // 逐个删除购物车商品
    for (const id of cartItemIds) {
      await request.delete('/cart/delete', { params: { id } });
    }
    
    return true;
  } catch (error) {
    console.error('删除购物车商品失败:', error);
    ElMessage.warning('订单已创建，但部分商品可能未从购物车中移除');
    return false;
  }
}

// 返回购物车
const backToCart = () => {
  router.push('/cart')
}

// 处理图片URL
const getImgUrl = (url) => {
  if (!url) return '';

  // 确保有服务器地址前缀
  let fullUrl = url;
  if (url.startsWith('/uploads/')) {
    fullUrl = SERVER_BASE_URL + url;
  }

  return fullUrl;
}

// 页面加载时获取必要数据
onMounted(() => {
  if (!checkLoginStatus() || !getCheckoutItems()) {
    return
  }
  getAddressList()
})
</script>

<template>
  <div class="checkout-container">
    <el-card class="checkout-card">
      <div class="checkout-header">
        <h2>订单结算</h2>
      </div>
      
      <div v-loading="loading">
        <!-- 收货地址选择 -->
        <div class="section-title">收货地址</div>
        <div class="address-section">
          <div v-if="addressList.length === 0" class="no-address">
            <p>您还没有收货地址</p>
            <el-button type="primary" @click="addNewAddress">添加新地址</el-button>
          </div>
          <div v-else class="address-list">
            <el-radio-group v-model="selectedAddressId">
              <div v-for="address in addressList" :key="address.id" class="address-item">
                <el-radio :label="address.id">
                  <div class="address-info">
                    <div class="address-header">
                      <span class="receiver">{{ address.receiverName }}</span>
                      <span class="phone">{{ address.receiverPhone }}</span>
                      <el-tag v-if="address.isDefault" size="small" type="success">默认</el-tag>
                    </div>
                    <div class="address-detail">{{ address.detailedAddress }}</div>
                  </div>
                </el-radio>
              </div>
            </el-radio-group>
            <div class="address-actions">
              <el-button type="primary" plain @click="addNewAddress">管理收货地址</el-button>
            </div>
          </div>
        </div>
        
        <!-- 商品列表 -->
        <div class="section-title">商品信息</div>
        <div class="goods-section">
          <el-table :data="cartItems" style="width: 100%">
            <el-table-column label="商品信息" min-width="400">
              <template #default="{ row }">
                <div class="commodity-info">
                  <el-image
                    :src="row.commodity.image && row.commodity.image.length > 0 ? getImgUrl(row.commodity.image[0]) : ''"
                    :preview-src-list="row.commodity.image.map(getImgUrl)"
                    fit="cover"
                    class="commodity-image"
                    preview-teleported
                  />
                  <div class="commodity-detail">
                    <h3>{{ row.commodity.name }}</h3>
                    <div class="commodity-tags">
                      <el-tag
                        v-for="tag in row.commodity.categoryTag"
                        :key="tag"
                        size="small"
                        class="tag"
                      >
                        {{ tag }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column label="单价" width="120">
              <template #default="{ row }">
                <span class="price">¥{{ row.commodity.price }}</span>
              </template>
            </el-table-column>
            
            <el-table-column label="数量" width="100" prop="quantity"></el-table-column>
            
            <el-table-column label="小计" width="120">
              <template #default="{ row }">
                <span class="subtotal">¥{{ (row.quantity * row.commodity.price).toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 支付方式 -->
        <div class="section-title">支付方式</div>
        <div class="payment-section">
          <el-radio-group v-model="paymentType">
            <el-radio label="ONLINE">在线支付</el-radio>
            <el-radio label="CASH">货到付款</el-radio>
          </el-radio-group>
          <div v-if="paymentType === 'CASH'" class="payment-tip">
            <el-alert
              title="选择货到付款，订单将自动标记为已付款状态"
              type="info"
              :closable="false"
              show-icon
            />
          </div>
        </div>
        
        <!-- 订单备注 -->
        <div class="section-title">订单备注</div>
        <div class="remark-section">
          <el-input
            v-model="orderRemark"
            type="textarea"
            :rows="2"
            placeholder="请输入订单备注（选填）"
            maxlength="200"
            show-word-limit
          ></el-input>
        </div>
        
        <!-- 订单金额 -->
        <div class="section-title">订单金额</div>
        <div class="amount-section">
          <div class="amount-item">
            <span>商品总额：</span>
            <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
          <div class="amount-item">
            <span>运费：</span>
            <span class="price">¥0.00</span>
          </div>
          <div class="amount-item total">
            <span>应付金额：</span>
            <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
        </div>
        
        <!-- 提交订单 -->
        <div class="submit-section">
          <div class="order-summary">
            <span class="summary-text">共 {{ totalQuantity }} 件商品，应付金额：</span>
            <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
          </div>
          <div class="action-buttons">
            <el-button @click="backToCart">返回购物车</el-button>
            <el-button 
              type="primary" 
              :loading="creatingOrder" 
              @click="submitOrder"
            >
              提交订单
            </el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.checkout-container {
  margin: 20px auto;
  width: 95%;
  max-width: 1200px;
}

.checkout-card {
  margin-bottom: 20px;
}

.checkout-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.checkout-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px;
  color: #333;
}

/* 地址样式 */
.address-section {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
}

.no-address {
  text-align: center;
  padding: 20px;
}

.address-list {
  display: flex;
  flex-direction: column;
}

.address-item {
  padding: 10px 0;
  border-bottom: 1px dashed #eee;
}

.address-item:last-child {
  border-bottom: none;
}

.address-info {
  margin-left: 5px;
}

.address-header {
  margin-bottom: 5px;
}

.receiver {
  font-weight: bold;
  margin-right: 10px;
}

.phone {
  color: #666;
  margin-right: 10px;
}

.address-detail {
  color: #666;
}

.address-actions {
  margin-top: 15px;
  text-align: right;
}

/* 商品信息样式 */
.goods-section {
  margin-bottom: 20px;
}

.commodity-info {
  display: flex;
  align-items: center;
}

.commodity-image {
  width: 60px;
  height: 60px;
  border-radius: 3px;
  margin-right: 10px;
}

.commodity-detail h3 {
  margin: 0 0 5px;
  font-size: 14px;
}

.commodity-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.tag {
  margin-right: 5px;
}

.price, .subtotal {
  color: #f56c6c;
  font-weight: bold;
}

/* 支付方式样式 */
.payment-section {
  padding: 15px 0;
}

.payment-tip {
  margin-top: 10px;
}

/* 金额信息样式 */
.amount-section {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.amount-item.total {
  font-weight: bold;
  font-size: 16px;
}

/* 提交订单样式 */
.submit-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.order-summary {
  font-size: 14px;
}

.summary-text {
  margin-right: 10px;
}

.total-price {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
</style> 